package org.janon.httpproxy.server.method;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import org.janon.httpproxy.ClientReadFromServer;
import org.janon.httpproxy.HttpModel;
import org.janon.httpproxy.HttpSession;
import org.janon.httpproxy.HttpUtil;
import org.janon.httpproxy.Log;
import org.janon.httpproxy.RequestLogStream;

public class ConnectMethod
{
	public static ClientReadFromServer doMethod(HttpModel httpModel, BufferedInputStream server_in, BufferedOutputStream server_out, BufferedInputStream client_in, BufferedOutputStream client_out, HttpSession session, RequestLogStream rls) throws Exception
	{
		String connectKey = ConnectMap.getInstance().add(server_out,server_in,client_out,rls);
		client_out.write((httpModel.getHttpType() + " 200 OK" + HttpUtil.CRLF).getBytes());
		HttpUtil.sendInitHeader(client_out);
		client_out.write(("Set-Cookies: " + connectKey + HttpUtil.CRLF).getBytes());
		client_out.write(HttpUtil.CRLF.getBytes());
		client_out.flush();
		
		Log.getInstance().writeRecordToFile(rls.getInputStream(), (httpModel.getHttpType() + " 200 OK"));
		Log.getInstance().writeRecordToFile(rls.getInputStream(), ("Set-Cookies: "+connectKey));
		Log.getInstance().writeRecordToFile(rls.getInputStream(), "");
		
		while(ConnectMap.getInstance().getFlag(connectKey).equals(connectKey))
		{
			Thread.sleep(5000);
		}

		return null;
	}
}
